package com.threeti.mecool.web.util;

import com.threeti.mecool.shared.util.AbstractTreeNode;
import com.threeti.mecool.shared.util.TreeNodeWithChilds;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public final class JsTreeDataUtil {

	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static <TK extends Serializable> void buildTree(AbstractTreeNode<TK> entryNode, List<Map<String, Object>> treeMap) {
		Map<String, Object> e = new HashMap<String, Object>();
		e.put("id", entryNode.getId());
		e.put("pId", entryNode.getParent() != null ? entryNode.getParent().getId() : 0);
		e.put("name", String.valueOf(entryNode.getName()));
		treeMap.add(e);

		if (CollectionUtils.isEmpty(entryNode.getChilds())) {
			return;
		} else {
			for (AbstractTreeNode childNode : entryNode.getChilds()) {
				buildTree(childNode, treeMap);
			}
		}
	}

	public static <TK extends Serializable> void buildTree(TreeNodeWithChilds<TK> entryNode, List<Map<String, Object>> treeMap,MapDataAssembling dataAssembling) {
		treeMap.add(dataAssembling.assembling(entryNode));
		if (CollectionUtils.isEmpty(entryNode.getChilds())) {
			return;
		} else {
			for (TreeNodeWithChilds childNode : entryNode.getChilds()) {
				buildTree(childNode, treeMap,dataAssembling);
			}
		}
	}


	public interface MapDataAssembling{
		Map assembling(TreeNodeWithChilds entryNode);
	}

	public interface MapTreeNodeDataAssembling{
		Map assembling(AbstractTreeNode entryNode);
	}

	public static <TK extends Serializable> void buildTree(AbstractTreeNode<TK> treeNode,List<Map<String, Object>> treeMap, MapTreeNodeDataAssembling treeNodeDataAssembling) {
		Map data = treeNodeDataAssembling.assembling(treeNode);
		if(data!=null){
			treeMap.add(data);
		}
		if (CollectionUtils.isEmpty(treeNode.getChilds())) {
			return;
		} else {
			for (AbstractTreeNode childNode : treeNode.getChilds()) {
				buildTree(childNode, treeMap,treeNodeDataAssembling);
			}
		}
	}
}
